package com.suxin.datahub.database;

import com.suxin.datahub.core.DataBaseMetaService;
import com.suxin.datahub.core.meta.MySqlDataBaseMetaServiceImpl;
import com.suxin.datahub.core.meta.OracleDataBaseMetaServiceImpl;
import com.suxin.datahub.core.query.MySqlQueryServiceImpl;
import com.suxin.datahub.core.query.OracleQueryServiceImpl;
import com.suxin.datahub.domain.DataSourceDomain;
import com.suxin.datahub.enums.DbType;
import com.suxin.datahub.util.LocalCacheUtil;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;

/**
 * @Classname DataBaseFactory
 * @Description [ DataBaseFactory ]
 * @Author Tang
 * @Date 2020/11/10 10:25
 * @Created by ASUS
 */
@Slf4j
public class DataBaseFactory {

    public static DataBaseMetaService getMetaService(DataSourceDomain dataSourceDomain) {

        String name = dataSourceDomain.getDbType().getName();

        if (DbType.MYSQL.getName().equals(name)) {
            return new MySqlDataBaseMetaServiceImpl(
                    new MySqlQueryServiceImpl(),dataSourceDomain
            );
        } else if (DbType.ORACLE.getName().equals(name)) {
            return new OracleDataBaseMetaServiceImpl(
                    new OracleQueryServiceImpl(),dataSourceDomain
            );
        }
        return null;
    }

    public static Connection getDataSource(DataSourceDomain dataSourceDomain){
        // 缓存中获取连接
        LocalCacheUtil cacheUtil = LocalCacheUtil.getInstance();
        Connection connection = (Connection) cacheUtil.get(dataSourceDomain.getName());
        if (connection != null) {
            return connection;
        }
        // 使用连接池 获取数据源
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(dataSourceDomain.getUrl());
        hikariConfig.setDriverClassName(dataSourceDomain.getDriverClassName());
        hikariConfig.setUsername(dataSourceDomain.getUsername());
        hikariConfig.setPassword(dataSourceDomain.getPassword());
        // 连接失败，报错
        HikariDataSource dataSource = new HikariDataSource(hikariConfig);
        try {
            connection = dataSource.getConnection();
        } catch (Exception throwables) {
            log.error("获取数据库连接失败!" + throwables.getMessage());
        }
        // 缓存 5 分钟
        cacheUtil.set(dataSourceDomain.getName(),new LocalCacheUtil.CacheValue(
                3600L,connection
        ));
        return connection;
    }

}